package com.gliese.bambook.service.snb.impl;

import java.util.Date;

import org.apache.commons.lang.time.DateFormatUtils;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.dom4j.Document;
import org.dom4j.DocumentHelper;
import org.dom4j.Element;

import com.gliese.bambook.object.Snbc;
import com.gliese.bambook.service.snb.interfaces.CreateSnbcService;
import com.gliese.bambook.util.SnbUtils;
import com.gliese.util.file.FileUtils;

public class BambookCreateSnbcService implements CreateSnbcService {
	private String absoluteSnbPath = null;
	private Snbc snbc = null;
	final Log log = LogFactory.getLog(BambookCreateSnbcService.class);

	@Override
	public void createSnbc(Snbc snbc, String snbcFileName, boolean first) {
		this.snbc = snbc;
		if (first)
			prepareDirectorysAndFiles();
		// generate *snbc
		Document doc = DocumentHelper.createDocument();
		Element root = doc.addElement("snbc");
		Element head = root.addElement("head");
		Element title = head.addElement("title");
		title.addCDATA(snbc.getSnbcTitle());
		Element body = root.addElement("body");
		for (String strParaContext : snbc.getSnbcContextItems()) {
			if (!"".equals(strParaContext.trim()))
				body.addElement("text").addCDATA(strParaContext.trim());
		}
		String absPathOfSnbc = absoluteSnbPath + "snbc"
				+ System.getProperty("file.separator") + snbcFileName;
		SnbUtils.wirteDocument(doc, absPathOfSnbc);
	}

	// generate book.snbf
	private void generateBookDotSnbf() {
		Document doc = DocumentHelper.createDocument();
		Element root = doc.addElement("book-snbf");
		root.addAttribute("version", "1.0");
		Element head = root.addElement("head");
		head.addElement("name").addCDATA(
				" News in " + snbc.getUrl() + " Every day");
		head.addElement("author").addCDATA("Hyvi Team");
		head.addElement("language").addCDATA("zh-CN");
		head.addElement("rights").addCDATA("created by Hyvi");
		head.addElement("publisher").addCDATA(snbc.getUrl());
		head.addElement("generator").addCDATA("News Every Day");
		head.addElement("created").addCDATA(
				DateFormatUtils.ISO_DATE_FORMAT.format(new Date()));
		head.addElement("abstract").addCDATA("News From " + snbc.getUrl());
		head.addElement("cover").addText(snbc.getUrl() + "_" + "cover.png");// FIXME
		String absPahtOfBookSnbf = absoluteSnbPath + "snbf"
				+ System.getProperty("file.separator") + "book.snbf";
		SnbUtils.wirteDocument(doc, absPahtOfBookSnbf);
	}

	private void prepareDirectorysAndFiles() {
		String fileSeparator = System.getProperty("file.separator");
		String snbSinaTodayPath = SnbUtils.getSnbTodayAbsPath(snbc);
		// snbc/images
		FileUtils.mkdirIfNotExists(snbSinaTodayPath + "snbc" + fileSeparator
				+ "images");
		// snbf
		FileUtils.mkdirIfNotExists(snbSinaTodayPath + "snbf");

		this.absoluteSnbPath = snbSinaTodayPath;
		// book.snbf
		generateBookDotSnbf();
	}
}
